package com.sunnay.constant;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import cn.hutool.json.JSONObject;
import com.gaby.commons.okhttp.OkHttpUtils;
import com.sunnay.entity.UserBidEntity;
import com.sunnay.util.CommUtils;
import com.sunnay.util.OkHttpClientUtils;
import com.sunnay.vo.live.AlsoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lyw
 * @discrption
 * @createTime 2022-11-21 12:59
 */
@Slf4j
public class SendConstant {

    private AlsoVo alsoVo = new AlsoVo();

    private final Map<String,String> map = new HashMap<>();

    private static OkHttpUtils okHttpUtils = null;

    //初始化发言信息
    static {
        okHttpUtils = new OkHttpUtils();
    }

    public SendConstant(UserBidEntity userBidEntity){
        map.put("Cookie","ut="+userBidEntity.getUt());
    }

    public void userSign(String shopUri){
        try{
            String result = okHttpUtils.post(CommUtils.LiveUtils.SEND_USER_SIGN+shopUri,"",OkHttpUtils.FORM_DATA,map);
            log.info("userSign:{}",result);
            if(StringUtils.isNotBlank(result)){
                JSONObject jo = JSONUtil.parseObj(result);
                String code = jo.getStr("code");
                if(StringUtils.equals(code,"0")){
                    alsoVo.setUserSig(jo.getJSONObject("data").getStr("userSig"));
                    alsoVo.setHeadImg(jo.getJSONObject("data").getStr("headimgurl"));
                }
            }
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    public void userLogin(String userInfoUri){
        try{
            String url = String.format(CommUtils.LiveUtils.SEND_USER_LOGIN,userInfoUri,alsoVo.getUserSig(),System.currentTimeMillis()/1000);
            String result = okHttpUtils.post(url, "{\"State\":\"Online\"}",OkHttpUtils.FORM_DATA,map);
            log.info("userLogin:{}",result);
            if(StringUtils.contains(result,"A2Key")){
                JSONObject jo = JSONUtil.parseObj(result);
                alsoVo.setA2Key(jo.getStr("A2Key"));
                alsoVo.setTinyId(jo.getStr("TinyId"));
            }
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    public void applyGroup(String timId){
        try{
            String url = String.format(CommUtils.LiveUtils.SEND_USER_GOURP,alsoVo.getTinyId(),alsoVo.getA2Key(),System.currentTimeMillis()/1000);
            String result = okHttpUtils.post(url, "{\"GroupId\":\"" + timId + "\"}",OkHttpClientUtils.FORM_DATA,map);
            log.info("applyGroup:{}",result);
            if(StringUtils.contains(result,"LongPollingKey")){
                JSONObject jo = JSONUtil.parseObj(result);
                alsoVo.setLongPollingKey(jo.getStr("LongPollingKey"));
            }
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    public void getMsg(){
        try{
            String url = String.format(CommUtils.LiveUtils.SEND_USER_MSG,alsoVo.getTinyId(),alsoVo.getA2Key(),System.currentTimeMillis()/1000);
            String result = okHttpUtils.post(url, "{\"USP\":1,\"StartSeq\":" + alsoVo.getMsgSeq() + ",\"HoldTime\":90,\"Key\":\"" + alsoVo.getLongPollingKey() + "\"}",OkHttpClientUtils.FORM_DATA,map);
            log.info("getMsg:{}",result);
            if(StringUtils.contains(result,"NextSeq")){
                com.alibaba.fastjson.JSONObject jo = com.alibaba.fastjson.JSONObject.parseObject(result);
                alsoVo.setNextSeq(jo.getString("NextSeq"));
                alsoVo.setKey(jo.getString("Key"));
                JSONArray jsonArray = JSONArray.parseArray(jo.getString("RspMsgList"));
                alsoVo.setMsgRandom(jsonArray.getJSONObject(0).getString("MsgRandom"));
            }
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    public String startSendMessage(String message,String timId,String userInfoUri,Integer grade){
        try{
            String json = "{\"GroupId\":\"" + timId + "\",\"From_Account\":\"" + userInfoUri+ "\",\"Random\":" + alsoVo.getMsgRandom() + ",\"MsgBody\":[{\"MsgType\":\"TIMTextElem\",\"MsgContent\":{\"Text\":\"" + message + "\"}},{\"MsgType\":\"TIMCustomElem\",\"MsgContent\":{\"Data\":\"{\\\"user_img\\\":\\\"" + alsoVo.getHeadImg() + "\\\",\\\"buyerLevel\\\":" + grade + ",\\\"buyerLevel\\\":" + grade+"}\",\"Desc\":null,\"Ext\":null}}],\"MsgPriority\":\"COMMON\"}";
            //String url = String.format(CommUtils.LiveUtils.SEND_USER_SEND_MSG,alsoVo.getTinyId(),alsoVo.getA2Key(),System.currentTimeMillis()/1000);
            String url = String.format(CommUtils.LiveUtils.SEND_USER_SEND_MSG,alsoVo.getTinyId(),alsoVo.getA2Key(),System.currentTimeMillis()/1000);
            String result = okHttpUtils.post(url, json, OkHttpClientUtils.FORM_DATA,map);
            //Proxy proxy = getProxy();
            /*String result = HttpUtil.createPost(url)
                    .setConnectionTimeout(8000)
                    .setReadTimeout(8000)
                    .setProxy(proxy)
                    .addHeaders(map)
                    .contentType("application/x-www-form-urlencoded")
                    .body(json)
                    .execute()
                    .body();*/
            log.debug("发送消息:"+result);
            com.alibaba.fastjson.JSONObject jo = com.alibaba.fastjson.JSONObject.parseObject(result);
            if(StringUtils.contains(result,"OK")){
                //okHttpUtils.post(CommUtils.SEND_ADD_ACTIVE_MSG, "roomId="+tLiveUser.getRoomId(),OkHttpClientUtils.FORM_DATA,map);
                //okHttpUtils.post(CommUtils.SEND_ADD_ROOM_MSG, "quickReplyKey=5&type=0&userRoleType=0&roomId="+tLiveUser.getRoomId()+"&content="+ URLEncoder.encode(message,"UTF-8"),OkHttpClientUtils.FORM_DATA,map);
                return "success";
            }
            return jo.getString("ErrorInfo");
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
        return null;
    }

    private Proxy getProxy(){
        Authenticator.setDefault(new Authenticator() {
                                     public PasswordAuthentication getPasswordAuthentication() {
                                         //serverProxyUsername 用户名
                                         //serverProxyPassword 密码
                                         return new PasswordAuthentication(CommUtils.proxyUser, CommUtils.proxyPass.toCharArray());
                                     }
                                 }
        );
        Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(CommUtils.proxyServer,CommUtils.proxyPort));
        return proxy;
    }
}
